package com.zlcx.tz.live.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.FeatureDescriptor;
import java.util.stream.Stream;

/**
 * DES :
 * 2017/12/6 12:08
 * CREATE BY zhangxiaobin
 */
public class UpdateUtil {

    /**
            * 复制对象的非空属性
     * 例如(例子中的对象是bean, 不是JSONObject, 对象无需是同一个class, 只要有共同的属性名称就可以):
            * source={"name":"a","address":null, "age":30},
            * target={"name":"b", "address"="address", "note"="note"}
     * <p>
     * 执行copyNonNullProperties(source,target)之后,
     * <p>
     * target={"name":"a", "address"="address", "note"="note"}
     *
             * @param source
     * @param target
     */
    public static void copyNonNullProperties(Object source, Object target) {

        final BeanWrapper wrappedSource = new BeanWrapperImpl(source);

        String[] nullPropertyNames = Stream.of(wrappedSource.getPropertyDescriptors())
                .map(FeatureDescriptor::getName)
                .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
                .toArray(String[]::new);

        BeanUtils.copyProperties(source, target, nullPropertyNames);
    }


}
